package com.base.fragment;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.CallSuper;
import android.support.annotation.LayoutRes;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import com.base.activity.BaseActivity;
import com.base.widget.TitleBar;
import com.uitls.utils.DisplayUtils;


public abstract class BaseFragment extends Fragment {
    //是否初始化成功，在initData之后调用
    protected boolean mHasInit = false;
    //多个fragment切换时，是否是可视状态
    private boolean mIsVisibleToUser = false;
    protected boolean mResumed;
    //是否为ViewPagerAdapter下面的Fragment
    private boolean mIsViewPagerFragment = false;

    private View mContentView;  //除标题栏外的view
    private TitleBar mTitleBar; //标题栏
    protected boolean isCreate;

    protected Context mContext;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = getContext();
        isCreate = true;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);

        int layoutId = getLayoutId();
        if (layoutId > 0) {
            mContentView = inflater.inflate(layoutId, container, false);

            if (useDynamicTitleBar()) {
                LinearLayout linearLayout = new LinearLayout(getActivity());
                linearLayout.setOrientation(LinearLayout.VERTICAL);
                View titleBar = getCustomTitleBar();
                if (titleBar == null) {
                    mTitleBar = new TitleBar(getActivity());
                    titleBar = mTitleBar;
                }
                //添加标题栏
                linearLayout.addView(titleBar, new LinearLayout.LayoutParams(
                        LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));

                //添加view
                linearLayout.addView(mContentView, new LinearLayout.LayoutParams(
                        LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));

                return linearLayout;
            } else {
                return mContentView;
            }
        } else {
            mContentView = getCustomView(inflater.getContext());
        }

        return mContentView;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView(savedInstanceState);
        /**
         * 如果是viewpager下的fragment,setUserVisibleHint的显示会先与此方法调用，contentView还没创建，无法遍历
         * mIsVisibleToUser是为true才执行是避免在viewpager下由于未显示的fragment覆盖掉显示的fragment
         * mIsViewPagerFragment是标志在不是viewpager的情况，setUserVisibleHint不会调用，必须通过此方法来找
         */
        if (mIsVisibleToUser || !mIsViewPagerFragment) {
            processFirstVisibleToUser(true);
        }
        mHasInit = true;
    }

    /**
     * 设置布局,如果子类不想设置，返回0就可以
     */
    protected abstract @LayoutRes
    int getLayoutId();

    /**
     * 初始化布局
     */
    protected abstract void initView(Bundle savedInstanceState);

    /**
     * 动态加载布局文件
     *
     * @param layoutResID
     * @param root
     * @return
     */
    protected View inflate(int layoutResID, ViewGroup root) {
        return LayoutInflater.from(getActivity()).inflate(layoutResID, root);
    }

    /**
     * 查找控件
     *
     * @param id
     * @return
     */
    protected <T extends View> T $(int id) {
        return (T) getView().findViewById(id);
    }

    protected <T extends View> T $(int id, View view) {
        return (T) view.findViewById(id);
    }

    /**
     * 要使用动态titlebar时，必须复写此方法，并返回true
     */
    protected boolean useDynamicTitleBar() {
        return false;
    }

    /**
     * 复写此方法，返回自定义的titlebar
     *
     * @return 返回自定义的titleBar
     */
    protected View getCustomTitleBar() {
        return null;
    }

    protected View getContentView() {
        return mContentView;
    }

    protected TitleBar getTitleBar() {
        return mTitleBar;
    }

    protected View getCustomView(Context context) {
        return null;
    }

    /**
     * 设置title
     * 如果不是用默认的TitleBar，不能设置此属性
     *
     * @param title
     */
    protected void setTitle(String title) {
        if (mTitleBar != null) {
            mTitleBar.setTitle(title);
        } else {
            throw new IllegalStateException("你没有使用默认的TitleBar，不能使用此方法设置标题");
        }
    }

    /**
     * 遍历找到viewGroup下面的第一个可滑动的View
     *
     * @param isVisibleToUser
     */
    private void processFirstVisibleToUser(boolean isVisibleToUser) {
        mIsVisibleToUser = isVisibleToUser;
        if (isVisibleToUser) {
            setSmoothToTopView(getScrollToTopView());
        } else {
            setSmoothToTopView(null);
        }
    }

    /**
     * 有些界面不需要滑动到顶部，可复写此方法，返回null
     *
     * @return
     */
    protected View getScrollToTopView() {
        return DisplayUtils.findFirstCanScrollView((ViewGroup) getContentView());
    }

    /**
     * 设置Activity的滑动View，如果fragment用了动态titleBar，需要更改测实现方式
     *
     * @param canScrollView
     */
    protected void setSmoothToTopView(View canScrollView) {
        if (useDynamicTitleBar() && mTitleBar != null) {
            mTitleBar.setSmoothToTopView(canScrollView);
        } else if (getActivity() instanceof BaseActivity) {
            ((BaseActivity) getActivity()).setSmoothToTopView(canScrollView);
        }
    }

    /**
     * fragmentManager调用hide跟show时的回调
     *
     * @param hidden
     */
    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        processFirstVisibleToUser(!hidden);
    }

    /**
     * viewPager显示或隐藏Fragment时的回调
     *
     * @param isVisibleToUser
     */
    @CallSuper
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        mIsViewPagerFragment = true;

        processFirstVisibleToUser(isVisibleToUser);
//        if (isVisibleToUser) {
//            /**
//             * 用于fragment嵌套fragment的情况，当点击父fragment时，父fragment也要回调子fragment的setUserVisibleHint方法
//             */
//            List<Fragment> fragments = getChildFragmentManager().getFragments();
//            if (fragments != null && fragments.size() > 0) {
//                for (Fragment fragment : fragments) {
//                    if (fragment != null && fragment.getUserVisibleHint()) {
//                        fragment.setUserVisibleHint(true);
//                    }
//                }
//            }
//        }
    }

    @Override
    public void onPause() {
        super.onPause();
        mResumed = false;
    }

    @Override
    public void onResume() {
        super.onResume();
        mResumed = true;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        release();
    }

    protected abstract void release();

    public void setSpringViewEnable(boolean springViewEnable) {

    }

}
